package com.servlet3.demo2.initializer;

import com.servlet3.demo2._type.A;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;


/**
 * SPI机制：
 * 在根目录下创建一个 /META-INF/services/javax.servlet.ServletContainerInitializer 文件，
 * 内容为 com.servlet3.demo2.initializer.MyServletContainerInitializer
 */
@HandlesTypes(A.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> set, ServletContext ctx) throws ServletException {
        System.out.println("====> tomcat 启动了");

        List<A> list = new LinkedList<A>();

        if (set != null) {
            for (Class<?> waiClass : set) {
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        A.class.isAssignableFrom(waiClass)) {
                    try {
                        list.add((A) waiClass.newInstance());
                    } catch (Throwable ex) {
                        throw new ServletException("Failed to instantiate A class", ex);
                    }
                }
            }
        }

        if (list.isEmpty()) {
            return;
        }

        for (A a : list) {
            a.test();
        }
    }
}
